<?php

namespace App\Http\Rest\Admin\Resource;

use App\Foundation\PasswordHelper;
use Framework\Foundation\Config;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Request\ServerRequest;
use Framework\Foundation\Response\ResponseGen;
use GuzzleHttp\Cookie\SetCookie;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;

class Token
{
    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Envms\FluentPDO\Exception
     */
    public function getList(array $restParams, ServerRequest $request)
    {
        return $this->add($restParams, $request);
    }

    public function getInfo(array $restParams)
    {
    }

    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Envms\FluentPDO\Exception
     */
    public function add(array $restParams, ServerRequest $request)
    {
        $username = $request->getIn("username");
        $password = $request->getIn("password");
        $remember = $request->getIn('remember');

        $ret = FDB::from('administrator')->where(['username' => $username])->fetch();
        if (empty($ret)) {
            return ResponseGen::error(400, "用户名或密码错误");
        }

        $pass = new PasswordHelper();
        $check = $pass->check($ret['password'], $password);
        if (!$check) {
            return ResponseGen::error(400, "用户名或密码错误");
        }

        $key = Config::instance()->get('admin.jwt.key');
        $token = (new Builder())
            ->withClaim("username", $ret['username'])
            ->withClaim("uid", $ret['administrator_id'])
            ->expiresAt(time() + 86400 * 30)
            ->getToken(new Sha256(), new Key($key));

        $response = ResponseGen::success(['token' => $token->__toString()]);
        if (!empty($remember)) {
            $cookie = new SetCookie(['Name' => 'AdminAuthorization', 'Value' => $token->__toString(), 'Expires' => time() + 86400 * 30]);
        } else {
            $cookie = new SetCookie(['Name' => 'AdminAuthorization', 'Value' => $token->__toString()]);
        }

        return $response->withHeader('Set-Cookie', $cookie->__toString());
    }


    public function edit(array $restParams, $request)
    {
    }


    public function delete(array $restParams)
    {
        $response = ResponseGen::success();
        $cookie = new SetCookie(['Name' => 'AdminAuthorization', 'Value' => '', 'Expires' => -1]);
        return $response->withHeader('Set-Cookie', $cookie->__toString());
    }
}
